#include "usb_cam_driver.hpp"
#include <opencv2/videoio.hpp>

UsbCamDriver::UsbCamDriver() {
    
    cap.open(0);
    if (!cap.isOpened()) {
        std::cerr << "Error: Could not open camera." << std::endl;
    } else {
        std::cout << "Camera opened successfully." << std::endl;
    }

    setCamera();
}

UsbCamDriver::UsbCamDriver(std::string video_path) {
    cap.open(video_path);
    if (!cap.isOpened()) {
        std::cerr << "Error: Could not open video file or camera." << std::endl;
    } else {
        std::cout << "Video file or camera opened successfully." << std::endl;
    }

    setCamera();
}

UsbCamDriver::~UsbCamDriver() {
    if (cap.isOpened()) {
        cap.release();
        std::cout << "Camera released!" << std::endl;
    }
}

void UsbCamDriver::setCamera(){

    cap.set(cv::CAP_PROP_FOURCC, cv::VideoWriter::fourcc('M', 'J', 'P', 'G'));
    // cap.set(cv::CAP_PROP_FOURCC, cv::VideoWriter::fourcc('Y', 'U', 'Y', 'V'));
    cap.set(cv::CAP_PROP_FRAME_WIDTH, this->params.image_width);  // 设置宽度
    cap.set(cv::CAP_PROP_FRAME_HEIGHT, this->params.image_height); // 设置高度
    cap.set(cv::CAP_PROP_FPS,  this->params.frame_rate);          // 设置帧率
    cap.set(cv::CAP_PROP_AUTO_EXPOSURE, this->params.auto_exposure); // 关闭自动曝光 (0=手动, 1=自动)
    cap.set(cv::CAP_PROP_EXPOSURE,  this->params.exposure_time);  // 设置曝光值
    cap.set(cv::CAP_PROP_GAIN,  this->params.gain);     // 设置增益

    
}

/**
* @brief 设置摄像头参数
* @param params 摄像头参数结构体,参数需全部填写
*/
void UsbCamDriver::setCamera(const CameraParameters params) {
    this->params = params;
    setCamera(); 
}

bool UsbCamDriver::get_frame(cv::Mat& frame){

    
    bool net = cap.read(frame); // 从摄像头或视频文件读取一帧
    if (!net) {
        std::cerr << "Error: Could not read frame from camera or video file." << std::endl;
        return false; // 如果读取失败，返回false
    }

    return true; // 返回读取的帧

}